package com.example.springboottest.controller;

import com.example.springboottest.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

@RestController

public class LoginController {



    @PostMapping("/login")

    public String login(User user){
//        System.out.println(user.getUsername() + ":::" + user.getPassword());
        if (ObjectUtils.isEmpty(user.getUsername()) || ObjectUtils.isEmpty(user.getPassword())){
            return "请输入用户名和密码";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            return "用户名不存在";
        }catch (AuthenticationException e){
            return "账号或密码错误";
        }catch (AuthorizationException e){
            System.out.println("没有权限");
            return "没有权限";
        }
        return "登陆成功";
    }
    @RequiresPermissions("add")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }

    @RequiresPermissions("query")
    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("msg","aa");
        return "index success!";
    }
}
